﻿<html DIR="LTR" xmlns:tool="http://www.microsoft.com/tooltip" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ddue="http://ddue.schemas.microsoft.com/authoring/2003/5" xmlns:MSHelp="http://msdn.microsoft.com/mshelp">
  <head>
    <META HTTP-EQUIV="Content-Type" CONTENT="text/html; CHARSET=utf-8" />
    <META NAME="save" CONTENT="history" />
    <title>使用存储过程读取大型数据的示例</title>
    
    <link rel="stylesheet" type="text/css" href="../local/Classic.css">
      
    </link>
    
    <script src="../local/script.js">
      
    </script><script src="../local/script_main.js">&amp;nbsp;</script>
  </head>
  <body>
    <!--Topic built:04/01/2010 05:03:28-->

    
    
    
    
    
    
    
    
    
    <div id="header">
      <table width="100%" id="topTable"><tr>
          <td align="left">
            <span id="headerBold">使用存储过程读取大型数据的示例</span>
          </td>
          <td align="right">
            
          </td>
        </tr></table>
      
      
      
    </div>
    <div id="mainSection">
      
        
        
    <font color="DarkGray">
      
    </font>
    <p />
    
    <p />
  
        <div id="introductionSection" class="section">
    <p>此 Microsoft SQL Server JDBC Driver 示例应用程序演示如何从存储过程中检索大型 OUT 参数。</p>
    <p>此示例的代码文件命名为 executeStoredProcedure.java，可以在以下位置找到：</p>
    <p>&lt;<i>安装目录</i>&gt;\sqljdbc_&lt;<i>版本</i>&gt;\&lt;<i>语言</i>&gt;\help\samples\adaptive</p>
  </div><h1 class="heading">要求</h1><div id="requirementsSection" class="section">
    <content xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">
      <p xmlns="">要运行此示例应用程序，需要访问 SQL Server 2005 AdventureWorks 示例数据库。还必须将 classpath 设置为包含 sqljdbc.jar 文件或 sqljdbc4.jar 文件。如果 classpath 缺少 sqljdbc.jar 项或 sqljdbc4.jar 项，示例应用程序将引发“找不到类”的常见异常。有关如何设置 classpath 的详细信息，请参阅<a href="6faaf05b-8b70-4ed2-9b44-eee5897f1cd0.htm">使用 JDBC 驱动程序</a>。</p>
      <div style="margin: .5em 1.5em .5em 1.5em" xmlns=""><b>注意：</b>
        Microsoft SQL Server JDBC Driver 提供两个类库文件：sqljdbc.jar 和 sqljdbc4.jar，具体使用哪个文件取决于首选的 Java 运行时环境 (JRE) 设置。有关选择哪个 JAR 文件的详细信息，请参阅 <a href="447792bb-f39b-49b4-9fd0-1ef4154c74ab.htm">JDBC 驱动程序的系统要求</a>。<p />
      </div>
      <p xmlns="">还必须在 SQL Server 2005 AdventureWorks 示例数据库中创建以下存储过程：</p>
      <div class="sampleCode" xmlns=""><span codeLanguage="other"><pre>CREATE PROCEDURE GetLargeDataValue 
  (@Document_ID int, 
   @Document_ID_out int OUTPUT, 
   @Document_Title varchar(50) OUTPUT,
   @Document_Summary nvarchar(max) OUTPUT)

AS 
BEGIN  
   SELECT @Document_ID_out = DocumentID, 
          @Document_Title = Title,
          @Document_Summary = DocumentSummary 
    FROM  Production.Document
    WHERE DocumentID = @Document_ID
END</pre></span></div>
    </content>
  </div><h1 class="heading">示例</h1><div id="codeExampleSection" class="section">
    <description xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">
      <content>
        <p xmlns="">在下面的示例中，示例代码建立到 SQL Server 2005 AdventureWorks 数据库的连接。接下来，示例代码创建示例数据并使用参数化查询更新 Production.Document 表。然后，示例代码通过使用 <a href="ec24963c-8b51-4838-91e9-1fbfa2347451.htm">SQLServerStatement</a> 类的 <a href="a9a9ffdd-7ce3-4e0a-907c-34d6a54e6865.htm">getResponseBuffering</a> 方法获取自适应缓冲模式，并执行 GetLargeDataValue 存储过程。请注意，从 JDBC Driver 2.0 发行版开始，responseBuffering 连接属性默认情况下设置为“adaptive”。</p>
        <p xmlns="">最后，示例代码显示使用 OUT 参数返回的数据，同时还演示如何在流中使用 <code>mark</code> 和 <code>reset</code> 方法以重新读取数据的任何部分。</p>
      </content>
    </description>
    <div class="sampleCode"><span codeLanguage="other"><pre>import java.sql.*;
import java.io.*;
import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement;

public class executeStoredProcedure {

    public static void main(String[] args) {
        // Create a variable for the connection string.
        String connectionUrl = 
           "jdbc:sqlserver://localhost:1433;" +
           "databaseName=AdventureWorks;integratedSecurity=true;";

        // Declare the JDBC objects.
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;  

        try {
          // Establish the connection.
          Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
          con = DriverManager.getConnection(connectionUrl);
 
          // Create test data as an example.
          StringBuffer buffer = new StringBuffer(4000);
          for (int i = 0; i &lt; 4000; i++) 
             buffer.append( (char) ('A'));

          PreparedStatement pstmt = con.prepareStatement(
               "UPDATE Production.Document " +
               "SET DocumentSummary = ? WHERE (DocumentID = 1)");
 
          pstmt.setString(1, buffer.toString());
          pstmt.executeUpdate();
          pstmt.close();

          // Query test data by using a stored procedure.
          CallableStatement cstmt = 
             con.prepareCall("{call dbo.GetLargeDataValue(?, ?, ?, ?)}");

          cstmt.setInt(1, 1);
          cstmt.registerOutParameter(2, java.sql.Types.INTEGER);
          cstmt.registerOutParameter(3, java.sql.Types.CHAR);
          cstmt.registerOutParameter(4, java.sql.Types.LONGVARCHAR);

          // Display the response buffering mode.
          SQLServerCallableStatement SQLcstmt = (SQLServerCallableStatement) cstmt;
          System.out.println("Response buffering mode is: " +
               SQLcstmt.getResponseBuffering());

          SQLcstmt.execute();
          System.out.println("DocumentID: " + cstmt.getInt(2));
          System.out.println("Document_Title: " + cstmt.getString(3));

          Reader reader = SQLcstmt.getCharacterStream(4);

          // If your application needs to re-read any portion of the value, 
          // it must call the mark method on the InputStream or Reader to 
          // start buffering data that is to be re-read after a subsequent
          // call to the reset method.	  	 	  
          reader.mark(4000);

          // Read the first half of data.
          char output1[] = new char[2000];
          reader.read(output1);
          String stringOutput1 = new String(output1);

          // Reset the stream.
          reader.reset();

          // Read all the data.
          char output2[] = new char[4000];
          reader.read(output2);
          String stringOutput2 = new String(output2);

          // Close the stream.
          reader.close();
      }
      // Handle any errors that may have occurred.
      catch (Exception e) {
          e.printStackTrace();
      }
      finally {
          if (rs != null) try { rs.close(); } catch(Exception e) {}
          if (stmt != null) try { stmt.close(); } catch(Exception e) {}
          if (con != null) try { con.close(); } catch(Exception e) {}
      }
   }
}
</pre></span></div>
  </div><span id="seeAlsoSpan"><h1 class="heading">请参阅</h1></span><div id="seeAlsoSection" class="section" name="collapseableSection"><a href="5b93569f-eceb-4f05-b49c-067564cd3c85.htm">处理大型数据</a><br /><br /></div><!--[if gte IE 5]>
			<tool:tip element="seeAlsoToolTip" avoidmouse="false"/><tool:tip element="languageFilterToolTip" avoidmouse="false"/><tool:tip element="roleInfoSpan" avoidmouse="false"/>
		<![endif]-->
      <div id="footer" class="section">
        
		<hr />
		
		<span id="fb" class="feedbackcss">
			
			
		</span>
		
		<a href="9bad553b-9e70-4696-8499-2e35f772a1e0.htm">
			
			© 2010 Microsoft Corporation。保留所有权利。
		</a>
 	
	
      </div>
    </div>
  </body>
</html>